/**
 * 配合测试多线程tcp服务，自定义协议的客户端
*/

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <time.h>

#include <arpa/inet.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "msg.h"

int init_tcp_client(char *server_ip, short int server_port)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket error: ");
        return -1;
    }

    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(struct sockaddr_in));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(server_port);
    serverAddr.sin_addr.s_addr = inet_addr(server_ip);

    if (connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr)) < 0)
    {
        perror("connect error: ");
        exit(EXIT_FAILURE);
    }

    return sockfd;
}

int main(int argc, char **argv)
{

    if (argc < 3)
    {
        fprintf(stderr, "%s <server_ip> <server_port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = init_tcp_client(argv[1], atoi(argv[2]));
    if (sockfd < 0)
    {
        exit(EXIT_FAILURE);
    }


    while (1)
    {
        char buf[1024] = {0}, recv_buf[1024] = {0};
         printf("> ");
        scanf("%s", buf);

        if (buf[0] == 'q' || buf[0] == 'Q')
        {
            break;
        }

        write_msg(sockfd, buf, strlen(buf));
        read_msg(sockfd, recv_buf, 1024);
    }

    close(sockfd);
    return 0;
}